package com.girlcoding.jianfei.util;

import java.io.ByteArrayOutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;

/**
 * The image util class
 * @author Tinker
 * @createDate 2011-6-20
 * @version v0.1
 */
public final class ImageUtil {

	/**
	 * Convert the drawable to the Bitmap
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawbleToBitmap(Drawable drawable) {
		Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight(),
				drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888:Bitmap.Config.RGB_565);
		
		Canvas canvas = new Canvas(bitmap);
		
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}

	/**
	 * Convert the byte array to the Bitmap
	 * @param bytes
	 * @return
	 */
	public static Bitmap BytesToBitmap(byte[] bytes) {
		if(bytes.length == 0)
			return null;
		return  BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
	}
	
	/**
	 * Convert the bitmap to the byte array
	 * @param bitmap
	 * @return
	 */
	public static byte[] BitmapToBytes(Bitmap bitmap) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}
}